<template>
  <div class="app-container" id="app-main">
    <!-- 查询和其他操作 -->
    <div class="filter-container" style="margin: 10px 0 10px 0">
      <div class="filter-container">
        <!-- <el-select v-model="value" :placeholder="$t('message.validate.input')+$t('message.role.CompanyTypePermission')" style="margin-right:10px">
          <el-option
            v-for="item in optionsJob"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
        <el-input
          v-model="query.roleName"
          clearable
          class="filter-item-left"
          style="width: 200px"
          size="small"
          :placeholder="$t('message.validate.inputrole')"
          @keyup.enter="handleFind"
        />
        <el-button class="filter-item-right" size="small" icon="el-icon-search" @click="handleFind">
          {{ $t('message.operate.search') }}
        </el-button>
        <el-button
          class="filter-item"
          size="small"
          type="primary"
          icon="el-icon-refresh"
          @click="handleReset"
        >
          {{ $t('message.operate.reset') }}
        </el-button>
      </div>
      <div class="filter-container2">
        <el-button
          v-limit="'XTGL:GNJS:ADD'"
          class="filter-item"
          size="small"
          type="primary"
          @click="handleAdd"
        >
          {{ $t('message.role.add') }}
        </el-button>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :max-height="maxHeight"
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column :label="$t('message.table.index')" width="50" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.role.name')" width="240" align="center">
        <template #default="scope">
          <span>{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.role.code')" width="240" align="center">
        <template #default="scope">
          <span>{{ scope.row.roleCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.role.CompanyTypePermission')" width="240" align="center">
        <template #default="scope">
          <span>{{ scope.row.unitTypeName }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.role.desc')" align="center">
        <template #default="scope">
          <span>{{ scope.row.roleDesc }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('message.table.createTime')"
        width="200"
        align="center"
        prop="createTime"
        sortable
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.operate.name')" fixed="right" width="200" align="center">
        <template #default="scope">
          <el-button
            v-limit="'XTGL:GNJS:EDIT'"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >
            {{ $t('message.operate.edit') }}
          </el-button>
          <el-button
            v-limit="'XTGL:GNJS:DELETE'"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >
            {{ $t('message.operate.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="title" :width="dialogWidth" append-to-body>
      <el-form ref="form" :model="form" :rules="dataRule">
        <el-form-item
          :label="$t('message.role.name')"
          :label-width="formLabelWidth"
          prop="roleName"
        >
          <el-input
            v-model="form.roleName"
            auto-complete="off"
            :placeholder="$t('message.validate.input')"
          />
        </el-form-item>

        <el-form-item
          :label="$t('message.role.code')"
          :label-width="formLabelWidth"
          prop="roleCode"
        >
          <el-input
            v-model="form.roleCode"
            auto-complete="off"
            :placeholder="$t('message.validate.input')"
          />
        </el-form-item>

        <el-form-item
          :label="$t('message.role.desc')"
          :label-width="formLabelWidth"
          prop="roleDesc"
        >
          <el-input
            v-model="form.roleDesc"
            auto-complete="off"
            :placeholder="$t('message.validate.input')"
          />
        </el-form-item>
        <!-- 范围 -->
        <!-- <el-form-item :label="$t('message.role.range')" :label-width="formLabelWidth" prop="dsType">
          <el-select
            v-model="form.dsType"
            :placeholder="$t('message.validate.input')"
            style="width: 100%"
            @change="changeScope"
          >
            <el-option
              v-for="item in dateScopes"
              :key="item.id"
              :label="item.des"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item
          :label="$t('message.role.CompanyTypePermission')"
          prop="unitType"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="form.unitType"
            :placeholder="$t('message.validate.input')"
            style="width: 100%"
            @change="changeUnitType"
          >
            <el-option
              v-for="item in unitTypes"
              :key="item.id"
              :label="item.itemText"
              :value="item.itemValue"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item
          v-if="form.dsType === 4"
          :label="$t('message.role.dataRole')"
          :label-width="formLabelWidth"
        >
          <treeselect
            v-model="deptIds"
            :options="deptData"
            multiple
            :placeholder="$t('message.validate.input')"
          />
        </el-form-item> -->
        <el-form-item
          :label="$t('message.role.jurisdiction')"
          :label-width="formLabelWidth"
          prop="multipleSelection"
        >
          <el-button style="height: 30px; padding: 0 10px;" size="small" @click="dialogVisible = true">
            {{ $t('message.role.jurisdiction') }}
          </el-button>
          <p style="height: 30px; margin: 0;" v-if="form.multipleSelection?.length != 0">
            已选择：<span
              v-for="item in form.multipleSelection"
              :key="item.powerId"
              style="margin-right: 5px"
              >{{ item?.powerName }}</span
            >
          </p>
          <!-- <el-input
            v-model="form.jurisdiction"
            auto-complete="off"
            :placeholder="$t('message.validate.input')"
          /> -->
        </el-form-item>
        <!-- 访问菜单 -->
        <!-- <el-form-item :label="$t('message.role.fetchMenu')" :label-width="formLabelWidth">
          <el-tree
            ref="menuTree"
            v-loading="menuLoading"
            :data="menuData"
            size="mini"
            show-checkbox
            node-key="menuId"
            :props="defaultProps"
            element-loading-text="拼命加载中"
            @check-change="handleMenuCheckChange"
          />

          <div style="padding-left: 24px; padding-top: 12px">
            <el-checkbox v-model="checkAll" :disabled="false" @change="handleCheckAll">
              <b>{{ $t('message.operate.all') }}</b>
            </el-checkbox>
          </div>
        </el-form-item> -->
      </el-form>
      <template #footer class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">
          {{ $t('message.operate.cancel') }}
        </el-button>
        <el-button size="small" type="primary" @click="submitForm">
          {{ $t('message.operate.confirm') }}
        </el-button>
      </template>
    </el-dialog>
    <RolePermissions
      ref="RolePermissions"
      v-if="dialogVisible"
      :id="id"
      v-model:dialogVisible="dialogVisible"
      @childFn="parentFn"
    ></RolePermissions>
  </div>
</template>

<script>
import { getRoles, addRole, updateRole, deleteRole, findRoleMenus, getPowers } from '../api/roles'
import { dataDictionary } from '../api/dict'
import { getMenus } from '../api/menu'
import { parseTime } from '@/utils/index'
import { getDeptTree } from '@/api/dept'
import { get } from 'lodash'
import { mapGetters } from 'vuex'
import RolePermissions from './components/RolePermissions/index.vue'

export default {
  components: {
    RolePermissions,
  },
  emits: ['close'],
  data() {
    return {
      tableData: [],
      keyword: '',
      title: '',
      dialogFormVisible: false, // 控制弹出框
      dialogVisible: false, //权限弹出框
      formLabelWidth: '120px',
      isEditForm: false,
      dateScopes: [
        {
          id: 1,
          des: this.$i18n.t('message.role.all'),
        },
        {
          id: 2,
          des: this.$i18n.t('message.role.level'),
        },
        {
          id: 3,
          des: this.$i18n.t('message.role.container'),
        },
        {
          id: 4,
          des: this.$i18n.t('message.role.custom'),
        },
      ],
      deptData: [],
      deptTreeProps: {
        label: 'name',
        children: 'children',
      },
      query: {
        roleName: '',
      },
      form: {
        roleId: 0,
        roleName: '',
        roleCode: '',
        roleDesc: '',
        roleMenus: [],
        dsType: 0,
        deptName: '',
        deptId: 1,
        rolePowerList: [],
        unitType: [],
        unitTypeName: '',
        multipleSelection: [],
      },
      // 分类菜单列表
      menuData: [],
      // tree配置项
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      selectRole: {},
      checkAll: false,
      menuIds: [],
      // 表单校验
      dataRule: {
        roleName: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'blur' },
        ],
        roleDesc: [
          { required: false, message: this.$i18n.t('message.validate.required'), trigger: 'blur' },
        ],
        roleCode: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'blur' },
        ],
        unitType: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'blur' },
        ],
        dsType: [
          { required: false, message: this.$i18n.t('message.validate.required'), trigger: 'blur' },
        ],
        multipleSelection: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'change' },
        ],
      },
      loading: false,
      id: '',
      multipleSelection: '',
      unitTypes: [],
      // deptIds: [],
      value: '',
      height: 0,
    }
  },
  computed: {
    // ...mapGetters(['ismobile']),
    maxHeight() {
      return this.height - 158
    },
  },
  created() {
    this.findTreeData()
    this.roleList()
    this.setDialogWidth()
    this.getdataDictionary()
  },
  mounted() {
    this.height = document.getElementById('app-main').offsetHeight
  },
  methods: {
    changeUnitType(val) {
      console.log(val, 'changeUnitType')
      this.unitTypes.forEach((item) => {
        if (item.itemValue == val) {
          this.form.unitTypeName = item.itemText
        }
      })
    },
    parseTime,
    // 获取角色
    roleList: function () {
      this.loading = true
      const params = {
        keyword: this.query.roleName,
        roleType: '1',
      }
      getRoles(params).then((response) => {
        this.tableData = response.data.data
        this.loading = false
      })
    },
    setDialogWidth() {
      // if (this.ismobile) {
      //   this.dialogWidth = '90%'
      // } else {
      //   this.dialogWidth = '50%'
      // }
      this.dialogWidth = '50%'
    },
    // 获取菜单树
    async findTreeData() {
      try {
        this.menuLoading = true
        const res = await getMenus()
        this.menuData = get(res, 'data.data', [])
        this.menuLoading = false
      } catch (err) {
        //
      }
    },
    //获取字典-单位权限类型
    async getdataDictionary() {
      dataDictionary(['SYS_ORG_UNIT_TYPE']).then((res) => {
        this.unitTypes = res.data.data.SYS_ORG_UNIT_TYPE
      })
    },
    // 树节点选择监听
    // handleMenuCheckChange(data, check) {
    //   if (check) {
    //     //  节点选中时同步选中父节点
    //     // const parentId = data.parentId
    //     // this.$refs.menuTree.setChecked(parentId, true, false)
    //   } else {
    //     // 节点取消选中时同步取消选中子节点
    //     if (data.children != null) {
    //       data.children.forEach(element => {
    //         this.$refs.menuTree.setChecked(element.id, false, false)
    //       })
    //     }
    //   }
    // },
    // // 全选操作
    // handleCheckAll() {
    //   if (this.checkAll) {
    //     const allMenus = []
    //     this.checkAllMenu(this.menuData, allMenus)
    //     this.$refs.menuTree.setCheckedNodes(allMenus)
    //   } else {
    //     this.$refs.menuTree.setCheckedNodes([])
    //   }
    // },
    // // 递归全选
    // checkAllMenu(menuData, allMenus) {
    //   menuData.forEach(menu => {
    //     allMenus.push(menu)
    //     if (menu.children) {
    //       this.checkAllMenu(menu.children, allMenus)
    //     }
    //   })
    // },

    handleFind: function () {
      this.roleList()
    },
    handleReset: function () {
      this.query = {
        roleName: '',
      }
      this.roleList()
    },
    // 添加角色
    handleAdd: function () {
      this.dialogFormVisible = true
      this.title = this.$i18n.t('message.role.add')
      this.form = {
        roleId: 0,
        roleName: '',
        roleCode: '',
        roleDesc: '',
        roleMenus: [],
        roleDepts: [],
        rolePowerList: [],
        // 数据权限类型
        dsType: '',
        deptName: '',
        deptId: 1,
        roleType: '1',
        multipleSelection: [],
      }
      //点击新增时，清除选中菜单
      // if (this.$refs.menuTree != undefined) {
      //   this.$refs.menuTree.setCheckedNodes([])
      // }
      // this.multipleSelection = []
      this.id = 0
      this.isEditForm = false
    },

    // 编辑角色
    handleEdit: function (row) {
      this.dialogFormVisible = true
      this.isEditForm = true
      this.title = this.$i18n.t('message.role.edit')
      this.form = row
      console.log(row)
      this.changeUnitType(this.form.unitType)
      this.id = row.roleId
      this.handleRoleSelectChange(row.roleId)
      // this.deptIds = []
      // if (this.form.dsType === 4) {
      //   this.findDeptTree()
      // }
      // for (let i = 0; i < this.form.roleDepts.length; i++) {
      //   this.deptIds[i] = this.form.roleDepts[i]
      // }
    },

    // 角色选择改变监听
    handleRoleSelectChange(id) {
      this.selectRole.id = id
      //菜单
      // findRoleMenus(id)
      //   .then(res => {
      //     this.$refs.menuTree.setCheckedNodes(res.data.data)
      //   })
      //   .catch(err => {
      //     console.error(err)
      //   })
      //权限
      getPowers(this.id)
        .then((res) => {
          this.form.multipleSelection = get(res, 'data.data', [])
        })
        .catch((err) => {
          console.error(err)
        })
    },

    handleDelete: function (row) {
      const that = this
      this.$confirm(this.$i18n.t('message.hint.isDelete'), this.$i18n.t('message.operate.hint'), {
        confirmButtonText: this.$i18n.t('message.operate.confirm'),
        cancelButtonText: this.$i18n.t('message.operate.cancel'),
        type: 'warning',
      }).then(() => {
        deleteRole(row.roleId).then((response) => {
          if (response.data.code === 200) {
            this.$message({
              type: 'success',
              message: response.data.msg,
            })
            that.roleList()
          } else {
            this.$message({
              type: 'error',
              message: response.data.msg,
            })
          }
        })
      })
    },
    parentFn(data) {
      this.form.multipleSelection = data
    },
    submitForm: function () {
      // if (this.form.dsType === 4 && this.deptIds.length === 0) {
      //   this.$message({
      //     message: this.$i18n.t('message.role.warning'),
      //     type: 'warning',
      //   })
      //   return
      // } else {
      // const depts = []
      // if (this.form.dsType === 4) {
      //   for (let i = 0; i < this.deptIds.length; i++) {
      //     depts.push(this.deptIds[i])
      //   }
      //   this.form.roleDepts = depts
      // }
      // }

      const roleId = this.selectRole.id !== undefined ? this.selectRole.id : '0'
      // const checkedNodes = this.$refs.menuTree.getCheckedNodes(false, false)
      const roleMenus = []
      // for (let i = 0, len = checkedNodes.length; i < len; i++) {
      //   const roleMenu = { roleId: roleId, menuId: checkedNodes[i].menuId }
      //   roleMenus.push(roleMenu)
      // }

      this.form.rolePowerList = this.form.multipleSelection.map((item) => ({
        roleId: roleId,
        powerId: item.id,
      }))
      // 得到选中树的角色id和菜单id
      this.form.roleMenus = roleMenus
      // 得到机构ids
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.isEditForm) {
            updateRole(this.form).then((response) => {
              if (response.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: response.data.msg,
                })
                this.dialogFormVisible = false
                this.roleList()
              } else {
                this.$message({
                  type: 'error',
                  message: response.data.msg,
                })
              }
            })
          } else {
            addRole(this.form).then((response) => {
              if (response.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: response.data.msg,
                })
                this.dialogFormVisible = false
                this.roleList()
              } else {
                this.$message({
                  type: 'error',
                  message: response.data.msg,
                })
              }
            })
          }
        }
      })
    },
    // 加载机构列表
    // findDeptTree: function() {
    //   getDeptTree().then(res => {
    //     this.deptData = res.data.data
    //   })
    // },
    changeScope() {
      this.deptIds = []
      if (this.form.dsType === 4) {
        this.findDeptTree()
      }
    },
  },
  // watch: {
  //   'form.unitType': {
  //     handler(val) {
  //       console.log(val, 'handler')
  //       this.unitTypes.forEach((item) => {
  //         if (item.itemValue == val) {
  //           this.form.unitTypeName = item.itemText
  //           console.log(this.form.unitTypeName,'this.form.unitTypeName');
  //         }
  //       })
  //     },
  //     immediate: true,
  //   },
  // },
}
</script>
